var comPageNum = 0;//分页公共页码
var isEdit = false;//是否编辑--判断是否跟新页码到首页
var subdomianall=''
getSubDomainList(1)
function getSubDomainList(val) {
    var user_data = {
        "pageNumber":1,
        "pageSize":10000,
        "name":"",
        "subDomain":"",
    }
    var succCallBack = function (data, status, response) {
        console.log(subdomianall)
        var sub_domian=''
        for (var i=0;i<data.data.data.length;i++){
            if (val==1){
                sub_domian+='<option value="'+data.data.data[i].subDomain+'" >'+data.data.data[i].name+'</option>'

            } else {
                if(subdomianall==data.data.data[i].subDomain){
                    sub_domian+='<option selected value="'+data.data.data[i].subDomain+'" >'+data.data.data[i].name+'</option>'

                }else {
                    sub_domian+='<option value="'+data.data.data[i].subDomain+'" >'+data.data.data[i].name+'</option>'

                }
            }
        }
        if (val==1){
            var sub_domianall='<option value="" selected>请选择</option>'
            $("#sub_domian").html(sub_domianall+sub_domian)

        } else {
            $("#subdomian").html(sub_domian)
        }
    };
    return web.doAjax(root.sroreinter.getSubDomainList, 'post', user_data, succCallBack,1);
}

function rotationChart() {
    //提交
    var user_data = {
        created_at_end:$("#logmax").val(),
        created_at_start:$("#logmin").val(),
        status:$("#status").val(),
        title:$("#text").val(),
        category_id:$("#category_id").val(),
        sub_domain:$("#sub_domian").val(),
    }
    //获取返回的数据
    var succCallBack = function (data, status, response) {
        console.log(data)
        if(data.errorCode=="0") {
            var dataSource = new Array();
            var table;   //table对象
            dataSource = [];
            var result=data.data;
            var q=0;
            $.each(result, function (i, field){
                q++
                var rowData = new Array();
                rowData.push(q);
                //序号0
                rowData.push(field.sub_domain);//所属域名
                rowData.push(field.title);
                rowData.push(field.category_id);
                rowData.push(field.status);
                rowData.push(field.started_at);
                rowData.push(field.end_in);
                rowData.push(field.sequence);
                rowData.push(field.created_name);
                rowData.push(field.created_at);

                rowData.push(field.resource_id);
                dataSource.push(rowData);
            });
            initDataTable(dataSource);
            return false
        }else{
            //报错
            var dttable = $('#rotationCharttable').dataTable( ); // 初始化dataTable，清空上一个值
            dttable.fnClearTable(); //清空一下table
            return false
        }
    };
    //给一个接口地址提交数据
    return web.doAjax(root.sroreinter.search_resource_conf, 'post', user_data, succCallBack);
    //获取数据之后如何展现在页面上
    function initDataTable(dataSource) {
        var dttable = $('#rotationCharttable').dataTable( ); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#rotationCharttable").DataTable({
            "fnDrawCallback" : function(){
                if(!isEdit){
                    comPageNum = getDataTablePageNum(dttable);
                }
                this.api().column(0).nodes().each(function(cell,i){
                    cell.innerHTML = i+1;
                    //权限控制函数
                    power()
                });
            },
            "autoWidth": false,
            "order": [[ 8, "desc" ]],
            "ordering": true,
            "searching": true,
            "paging": true,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu":[10,20,30],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />"
            },
            data: dataSource,
            columnDefs: [
                {"data":null,"targets":0 },
                {
                    "render": function(data,type,row,meta){
                        var val ='';
                        if(row[3]==23){
                            val="首页轮播图配置"
                        }else if(row[3]==24){
                            val="登陆页轮播图配置"
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function(data,type,row,meta){
                        var val ='<a onclick="newrotationChart(\''+row[10]+'\')">编辑</a><a class="ml-10" onclick="admin_start(\''+row[10]+'\')">删除</a>';
                        return val;
                    },
                    "targets": 10
                },
            ]
        });
        dttable.fnPageChange(comPageNum);
        isEdit = false;
        //权限控制函数
        power()
    }
}

function admin_start(id){
    layer.confirm('你确定要删除吗？',function(index){
        //此处请求后台程序，下方是成功后的前台处理……
        $.ajax({
            type: "post",
            url: root.sroreinter.delete_resource_conf,
            cache: false,  //禁用缓存
            dataType: "json",
            data: {
                resource_id:id,
            },
            //传入组装的参数
            success: function (data,user_data,succCallBack) {
                if(data.errorCode=="0") {
                    layer.msg('操作成功!', {icon: 6, time: 1000});
                    setTimeout( function () {
                        isEdit = true;
                        rotationChart();
                    },700);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        })
    });
}
//添加编辑
function newrotationChart(val) {
    $("#newrotationChart").modal("show")
    getSubDomainList(2)
    if(val==undefined){
        $("#rotationChartTitle").html("轮播图添加")
        if($("#categoryid").val()==23){
            $("#srctext").html("图片尺寸:740px*460px")
        }else if($("#categoryid").val()==24){
            $("#srctext").html("图片尺寸:1000px*450px")
        }
    }else {
        $("#rotationChartTitle").html("轮播图编辑")

        $.ajax({
            type: "post",
            url: root.sroreinter.search_resource_conf,
            cache: false,  //禁用缓存
            dataType: "json",
            data: {
                resource_id:val
            },  //传入组装的参数
            success: function (data) {
                var datas=data.data[0]
                subdomianall=datas.sub_domain
                $("#subdomian").val(datas.sub_domain)
                $("#categoryid").val(datas.category_id)
                $("#title").val(datas.title)
                $("#rotationChartsrc").attr("src",datas.image_path)
                $("#sequence").val(datas.sequence)
                $("#url").val(datas.image_url)
                $("#down_color").val(datas.color_value)
                $("#logmin1").val(datas.started_at)
                $("#logmax1").val(datas.end_in)
                $("#resourceids").val(val)
                if($("#categoryid").val()==23){
                    $("#srctext").html("图片尺寸:740px*460px")
                }else if($("#categoryid").val()==24){
                    $("#srctext").html("图片尺寸:1000px*450px")
                }
            }
        })
    }


}
function addBtnrotationChart(cen,ir) {
    $(cen).prev().prev().trigger('click');
}
// 提交上传图片
var fileimg=''
function getupfilerulrotationChart(can,e){
    var formData = new FormData();
    fileimg=$(can)[0].files[0]
    formData.append('file',$(can)[0].files[0]);
    $.ajax({
        url: root.inter.imgUpload,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        data: formData,
        success: function (data) {
            for(var i=0; i<data.length; i++){
                $(can).prev().val(data[0].reletivePath)
                $(can).prev().text(data[0].reletivePath)
                $("#rotationChartsrc").attr("src",data[0].fullPath)
            }
            $("#file").attr('type','text');
            $("#file").attr('type','file');

        }
    })
}
// 上传图片返现
function rotationChartputDataToPage(e,can) {
    verificationPicFileType(can)
    for(var i = 0; i < e.target.files.length; i++) {
        var file = e.target.files.item(i);
        if(!(/^image\/.*$/i.test(file.type))) {
            continue; //不是图片 就跳出这一次循环
        }
        var freader = new FileReader();
        freader.readAsDataURL(file);
        freader.onload = function (e) {
            var data = e.target.result;
            //加载图片获取图片真实宽度和高度
            var img = new Image();
            img.src= data;
            img.onload = function(){
                var width = img.width;
                var height = img.height;
                if($("#categoryid").val()==23){
                     if (width != 740 | height != 460){
                     $.Huimodalalert('图片尺寸限制为：740px*460px',2000);
                     file.value = "";
                     return file;
                 }else {
                     getupfilerulrotationChart(can,e)
                 }
                }else if($("#categoryid").val()==24){
                    if (width != 1000 | height != 450){
                        $.Huimodalalert('图片尺寸限制为：1000px*450px',2000);
                        file.value = "";
                        return file;
                    }else {
                        getupfilerulrotationChart(can,e)
                    }
                }

/*
                getupfilerulrotationChart(can,e)
*/

            };

        }
    }
}

function categoryids() {
    $("#rotationChartsrc").attr("src","")
    if($("#categoryid").val()==23){
        $("#srctext").html("图片尺寸:740px*460px")
    }else if($("#categoryid").val()==24){
        $("#srctext").html("图片尺寸:1000px*450px")
    }
}
// 图片类型验证
function verificationPicFileType(file) {
    var flag=false;
    var fileTypes = [".jpg", ".png"];
    var filePath = file.value;
    //当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false
    if(filePath){
        var isNext = false;
        var fileEnd = filePath.substring(filePath.indexOf("."));
        isNext = fileTypes.includes(fileEnd.toLowerCase());// 不区分图片后缀大小写格式
        for (var i = 0; i < fileTypes.length; i++) {
            if (fileTypes[i] == fileEnd) {
                isNext = true;
                flag= true;
                break;
            }
        }
        if (!isNext){
            $.Huimodalalert('图片格式支持jpg、png',2000);
            file.value = "";
            flag=false;
        }
    }
    return flag;
}
//保存
function rotationChartdetermine() {
    if($("#subdomian").val()==""){
        layer.msg('请选择所属二级域名', {icon: 5, time: 3000});
        return false
    }
    if($("#title").val()==""){
        layer.msg('请填写轮播图标题', {icon: 5, time: 3000});
        return false
    }
    if($("#rotationChartsrc").attr("src")==""){
        layer.msg('请选择图片', {icon: 5, time: 3000});
        return false
    }
    if($("#sequence").val()==""){
        layer.msg('请填写展示顺序', {icon: 5, time: 3000});
        return false
    }
    if($("#logmin1").val()==""||$("#logmax1").val()==""){
        layer.msg('请选择时间', {icon: 5, time: 3000});
        return false
    }
    var quzhi=JSON.parse(web.readCookie("loginData"))
    var formData = new FormData();
    if($("#resourceids").val()!=""){
        formData.append("resource_id",$("#resourceids").val());
    }
    formData.append("started_at",$("#logmin1").val());
    formData.append("end_in",$("#logmax1").val());
    formData.append("subDomain",$("#subdomian").val());
    formData.append("category_id",$("#categoryid option:selected").val());
    formData.append("title",$("#title").val());
    formData.append("file",fileimg);
    formData.append("sequence",$("#sequence").val());
    formData.append("image_url",$("#url").val());
    formData.append("created_name",quzhi.user.name);
    formData.append("created_by",quzhi.user.user_ID);
    formData.append("color_value",$("#down_color").val());
    console.log(formData)
    $.ajax({
        url: root.sroreinter.save_resource_conf,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        data: formData,
        success: function (data) {
            console.log(data)
            if (data.errorCode=="92"){
                layer.msg('您添加的开始时间小于已存在数据的结束时间!', {icon: 6, time: 3000});
            }
            if (data.errorCode=="94"){
                layer.msg(data.errorMessage, {icon: 6, time: 3000});
            }
            if(data.errorCode=="0") {
                layer.msg('操作成功!', {icon: 6, time: 1000});
                setTimeout( function () {
                    $("#newrotationChart").modal("hide")
                    rotationChart()
                    $("#subdomian").val("")
                    $("#categoryid").val("")
                    $("#title").val("")
                    $("#rotationChartsrc").attr("src","")
                    $("#sequence").val("")
                    $("#url").val("")
                    $("#down_color").val("")
                    $("#logmin1").val("")
                    $("#logmax1").val("")
                    $("#resourceids").val("")
                },700);
            }
            if (data.errorCode=="93"){
                layer.msg('开始时间不能大于结束时间,请重新查看', {icon: 6, time: 3000});
                return
            }
        }
    });
}
//取消
function rotationChartclos() {
    $("#newrotationChart").modal("hide")
    $("#subdomian").val("")
    $("#categoryid").val("")
    $("#title").val("")
    $("#rotationChartsrc").attr("src","")
    $("#sequence").val("")
    $("#url").val("")
    $("#down_color").val("")
    $("#logmin1").val("")
    $("#logmax1").val("")
    $("#resourceids").val("")

}